package com.clouddot.baipai.ui.dialog.H_Dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.ui.adapter.V_MainImageAdapter;

import java.util.ArrayList;
import java.util.List;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_TWO;


/**
 * Created by wxy on 2018/4/2.
 */

public class H_ImageDailog implements View.OnTouchListener,ViewPager.OnPageChangeListener{
    private Dialog Dialog;
    private FrameLayout frameLayout;
    private Context context;
    private ImageView close;
    private ViewPager viewPager;

    private int currentViewPagerItem = -1;
    private boolean isAutoPlay = true;

    private List<ImageView> mItems;
    private V_MainImageAdapter ImageAdapter;

    public H_ImageDailog(Context context, List<String> imgList) {
        this.context = context;
        this.mItems = addImageView(imgList);
        initView();
    }

    public ImageView getCloseView() {
        if (close == null) {
            close = frameLayout.findViewById(R.id.close);
        }
        return close;
    }

    private boolean flag = true;
    private AutoPlayThread autoPlayThread = null;

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        frameLayout = (FrameLayout) LayoutInflater.from(context).inflate(R.layout.h_d_image, null);
        viewPager = frameLayout.findViewById(R.id.viewPager);
        ImageAdapter = new V_MainImageAdapter(mItems, context);
        viewPager.setAdapter(ImageAdapter);
        viewPager.setPageMargin(10);
        viewPager.setOffscreenPageLimit(3);
//        viewPager.setPageTransformer(false, new AlphaAndScaleTransformer());
        viewPager.setOnTouchListener(this);
        viewPager.setOnPageChangeListener(this);
        if (!mItems.isEmpty()) {
            if (flag) {
                flag = false;
                autoPlayThread = new AutoPlayThread();
                autoPlayThread.start();
            }
        }
        currentViewPagerItem = 0;
    }

    public void showDialog() {
        Dialog = getDialog();
        Dialog.show();

    }

    public void closeDialog() {
        if (Dialog != null) {
            autoPlayThread.stopRun();
            Dialog.dismiss();
        }
    }

    private View view;

    public Dialog getDialog() {
        if (Dialog == null) {
            Dialog = new Dialog(context, R.style.ActionDialogStyle);
        }

        Dialog.setContentView(frameLayout);

        Window dialogWindow = Dialog.getWindow();

        view = dialogWindow.getDecorView();

        lock();

        view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int i) {
                lock();
            }
        });

        dialogWindow.setGravity(Gravity.CENTER);

        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.width = WindowManager.LayoutParams.MATCH_PARENT;

        lp.height = WindowManager.LayoutParams.MATCH_PARENT;

        dialogWindow.setAttributes(lp);

        Dialog.setCancelable(false);

        return Dialog;
    }


    private void lock() {
        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        view.setSystemUiVisibility(uiFlags);
    }


    private class AutoPlayThread extends Thread {

        private boolean stopFlag = false;

        @Override
        public void run() {
            while (!stopFlag) {
                try {
                    Thread.sleep(5000);
                    handler.sendEmptyMessage(MSG_TWO);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 通知线程需要停止
         */
        private void stopRun() {
            stopFlag = true;
        }
    }





    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_TWO:
                    if (isAutoPlay) {
                        ++currentViewPagerItem;
                        currentViewPagerItem = currentViewPagerItem % mItems.size();
                        viewPager.setCurrentItem(currentViewPagerItem);
                    }
                    break;
            }
        }
    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {}



    private List<ImageView> addImageView(List<String> strings) {
        mItems = new ArrayList<>();
        if (!strings.isEmpty()) {
                for (int i = 0; i < strings.size(); i++) {
                ImageView view0 = new ImageView(context);
                Glide.with(context).load(  Env.getAppContext().IP + strings.get(i)).asBitmap().placeholder(R.drawable.loading).diskCacheStrategy(DiskCacheStrategy.RESULT).into(view0);
                mItems.add(view0);
            }
        }
        return mItems;
    }
}



